#!/bin/bash
########################################################################
# script name:  check_stalepp.sh
# Used for:
# Author:       Martin Dumont
# Contributors:
# Version:      0.1
#
# (date format: date +'%Y/%m/%d')
#
# Date          Version Contributors    Modifications
# ----------    ------- ------------    -------------
# 2012/01/25    0.1     MDUMONT         initial
########################################################################
usage()
{
cat << STOP

usage: $0 [options] [ARG]

This script is used for ....

OPTIONS:
   -h               Host to check (see scripts/host file)
   -m               mail output

Ex.:
$0 -h aix
$0 -h aix -m
$0 -h aix_non_prd
STOP
}
#######################################
# Get parameters
#######################################
while getopts h:m OPTION
do
        case $OPTION in
        h)
                HOSTS=$(echo $OPTARG | sed 's/,/ /g' | sed 's/^-*//' | cut -d. -f1 | tr '[A-Z]' '[a-z]')
                ;;
        m)
                MAIL_s=1
                ;;
        \?)
                usage
                exit 1
                ;;
        *)
                usage
                exit 1
                ;;
        esac
done
#if [ $OPTIND = 1 ]; then usage; exit 1; fi
if [ -z "$HOSTS" ]; then HOSTS=localhost; fi
#######################################
# Variables and environnement
#######################################ENV=$(dirname `which $0`)/loadenv.sh
MAILTO="mtl_it_erp_technology_group_system_support@aero.bombardier.com"
BAENV=$(dirname `which $0`)/loadenv.sh
if [ -f $BAENV ]; then . $BAENV; else echo "No env library ($BAENV)"; exit 1; fi
SSH_OPTS=" -x -o ConnectTimeout=15 -o BatchMode=yes -o StrictHostKeyChecking=no -o LogLevel=quiet"
#######################################
# MAIN
#######################################
FILE=/tmp/stalepps.$RANDOM
NEWHOSTLIST=$(checkhost $HOSTS | grep -v Verifying)
for HOSTNAME in $NEWHOSTLIST
do
	#sudo -u saunix ssh $SSH_OPTS -T $HOSTNAME "for x in \`lsvg -Lo\`; do lsvg -L \$x | egrep 'VOLUME|STALE' | xargs | awk '{print \$3\" \"\$NF}'; done" | sed "s/^/$HOSTNAME /"
	cat <<-'EOF' | if [ "$HOSTNAME" != "localhost" ]; then sudo -u saunix ssh $SSH_OPTS $HOSTNAME "cat | sudo bash"; else cd /tmp; cat | sudo bash; fi
	for x in `lsvg -Lo`
	do
		VG=$(lsvg -L $x | egrep 'VOLUME|STALE' | xargs | awk '{print $3" "$NF}')
		STALEPPS=$(echo $VG | cut -d' ' -f2)
		if [ $STALEPPS -gt 0 ]; then STATUS=BAD; else STATUS=ok; fi
		echo $(uname -n) $x $STALEPPS $STATUS
	done
EOF
done | tee $FILE
if cat $FILE | grep -q BAD
then
	echo "ERROR: STALE PP'S, please verify" | tee -a $FILE
	if [ ! -z "$MAIL_s" ]; then cat $FILE | mail -s "ERROR: STALE PP'S, please verify" $MAILTO; fi
fi
rm $FILE
#######################################
exit 0
